import 'package:flutter/material.dart';
import 'package:scoped_model/scoped_model.dart';

/**
 * 管理状态的三种方式：
 *  1.数值 或者 回调方法从父的Widget 传递
 *  2.使用InheredWidget 提供 静态的of 方法 来引用数值和方法
 *  3.使用第三方的Scoped_model库 来管理状态
 */

//class StateManagementDemo extends StatefulWidget {
//  @override
//  State<StatefulWidget> createState() => StateManagementDemoState();
//}

//class StateManagementDemoState extends State<StateManagementDemo> {

class StateManagementDemo extends StatelessWidget {
  final int counter = 0;

//  inCreasement() {
//    setState(() {
//      counter++;
//    });
//  }

  @override
  Widget build(BuildContext context) {
    return
//        body: CounterProvider(
//          counter: counter,
//          increasement: inCreasement,
//          child: CounterWraper(),
//        ),
        ScopedModel(
            model: CounterModel(),
            child: Scaffold(
                appBar: AppBar(
                  title: Text('StateMangagementDemo'),
                  elevation: 0.0,
                ),
                body: CounterWraper(),
                floatingActionButton: ScopedModelDescendant<CounterModel>(
                  rebuildOnChange: false,
                  builder: (context, _, model) => FloatingActionButton(
                        onPressed: model.increasement,
                        elevation: 0.0,
                        child: Icon(Icons.add),
                      ),
                )));
  }
}

class CounterWraper extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Counter(),
    );
  }
}

class Counter extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
//    return ActionChip(
//      label: Text('counter =${CounterProvider.of(context).counter}'),
//      onPressed: CounterProvider.of(context).increasement,
//    );

    return ScopedModelDescendant<CounterModel>(
        builder: (context, _, model) => ActionChip(
              label: Text('${model.count}'),
              onPressed: model.increasement,
            ));
  }
}

class CounterProvider extends InheritedWidget {
  final int counter;
  final Widget child;
  final VoidCallback increasement;

  CounterProvider({this.counter, this.child, this.increasement});

  static CounterProvider of(BuildContext context) =>
      context.inheritFromWidgetOfExactType(CounterProvider);

  @override
  bool updateShouldNotify(InheritedWidget oldWidget) {
    return true;
  }
}

class CounterModel extends Model {
  int _count = 0;

  int get count => _count;

  increasement() {
    _count++;
    notifyListeners();
  }
}
